<script>
import request from '@/utils/request'
export default {
  name: 'Tabs',
  props: {
    vaule: {
      type: Array,
      default: () => []
    },
    filtersRaw: {
      type: Array,
      default: () => []
    },
    paramsRaw: {
      type: Object,
      default: () => ({})
    },
    url: {
      type: String,
      default: ''
    },
    method: {
      type: String,
      default: 'POST'
    },
    columns: {
      type: Array,
      default: () => []
    },
    selectionColumns: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: false
    },
    pageFlag: {
      type: Boolean,
      default: true
    },
    height: {
      type: [String, Number],
      default: 400
    }
  },
  data() {
    return {
      data: [],
      selections: [],
      page: 0,
      pageSize: 20,
      finished: false,
      isSearch: false,
      elTable: null,
      selectTable: null,
      loading: false
    }
  },
  computed: {
    sColumns() {
      if (this.selectionColumns && this.selectionColumns.length !== 0) {
        return this.selectionColumns
      }
      return this.columns
    }
  },
  watch: {
    url: {
      handler(v) {
        this.getData(v)
      }
    },
    // filtersRaw() {
    //   this.getData()
    // },
    // paramsRaw() {
    //   this.getData()
    // },
    selections: {
      handler(v) {
        this.$emit('input', v)
      }
    }
  },
  methods: {
    searchGetData() {
      this.page = 1
      this.finished = false
      this.loading = false
      this.isSearch = true
      return this.getData()
    },
    getData(url) {
      url = url || this.url
      if (!url || this.finished || this.loading) return
      url = url.replace(/\/slm-admin/g, '')
      const data = new FormData()
      data.append('filtersRaw', JSON.stringify(this.filtersRaw))
      data.append('paramsRaw', JSON.stringify(this.paramsRaw))
      data.append('pageFlag', this.pageFlag)
      data.append('order', 'desc')
      data.append('onlyCountFlag', false)
      if (this.pageFlag) {
        data.append('rows', this.pageSize)
        data.append('page', this.page)
        this.loading = true
      }
      return request({
        url,
        method: this.method,
        data
      }).then(res => {
        if (this.isSearch) {
          this.data = res.data.records || []
          this.isSearch = false
        } else {
          (res.data.records || []).forEach(e => {
            if (!this.data.includes(e)) {
              this.data.push(e)
            }
          })
        }
        this.$nextTick(() => {
          const uniques = this.selections.map(e => this.unique(e))
          this.data.forEach(e => {
            if (uniques.includes(this.unique(e))) {
              if (this.elTable && this.elTable.componentInstance) {
                this.elTable.componentInstance.toggleRowSelection(e, true)
              }
            }
          })
        })
        if (this.data.length >= res.data.total) {
          this.finished = true
        }
        this.page++
      }).finally(() => {
        this.loading = false
      })
    },
    unique(obj) {
      const keys = Object.keys(obj).sort()
      return keys.map(e => obj[e]).join(',')
    },
    rowClickHandle(row, column, event) {
      for (const item of this.columns) {
        if (column.property === item.prop && item.clickFun) {
          item.clickFun(row)
        }
      }
    },
    selectAllHandle(v) {
      this.selections = [...v]
    },
    selectHandle(selection, row) {
      if (this.selections.every(e => e !== row)) {
        this.selections.push(row)
      } else {
        const i = this.selections.indexOf(row)
        if (i !== -1) {
          this.selections.splice(i, 1)
        }
      }
    },
    // 删除选中项
    removeSelectRow(row, column, $index) {
      this.selections.splice($index, 1)
      const unique = this.unique(row)
      for (const e of this.data) {
        if (unique === this.unique(e)) {
          if (this.elTable && this.elTable.componentInstance) {
            this.elTable.componentInstance.toggleRowSelection(e, false)
          }
          break
        }
      }
    },
    removeSelectAll(table) {
      this.selections = []
      if (table.componentInstance) {
        table.componentInstance.clearSelection()
      }
    }
  },
  render(h) {
    const elColumns = this.columns.map((col, i) => {
      const c = { ...col }
      delete c.render
      delete c.formatData
      delete c.propEnum
      const scopedSlots = {}
      if (col.render) {
        scopedSlots.default = props => {
          const { row, column, $index } = props
          return col.render(h, row, column, $index)
        }
      } else if (col.formatData) {
        scopedSlots.default = props => {
          const { row, column, $index } = props
          return h('div', col.formatData(row, column, $index))
        }
      } else if (col.propEnum) {
        scopedSlots.default = props => {
          const { row } = props
          return h('c-dict-range-view', { props: {
            dictTypeCode: col.propEnum.dictTypeCode,
            value: row[col.prop],
            domainCode: col.propEnum.domainCode,
            appCode: col.propEnum.appCode
          }})
        }
      }
      return h('el-table-column', {
        props: {
          ...c
        },
        key: col.prop || i,
        scopedSlots
      })
    })
    if (this.multiple) {
      elColumns.unshift(h('el-table-column', {
        props: {
          type: 'selection'
        }
      }))
    }
    const elTable = h('el-table', { props: {
      data: this.data,
      headerRowClassName: 'table-list-header',
      height: this.height
    }, on: {
      'row-click': this.rowClickHandle,
      'select-all': this.selectAllHandle,
      'select': this.selectHandle
    }, ref: 'elTable' }, elColumns)
    this.elTable = elTable
    const selectColumns = this.sColumns.map((col, i) => {
      const c = { ...col }
      delete c.render
      delete c.formatData
      delete c.propEnum
      const scopedSlots = {}
      if (col.render) {
        scopedSlots.default = props => {
          const { row, column, $index } = props
          return col.render(h, row, column, $index)
        }
      } else if (col.formatData) {
        scopedSlots.default = props => {
          const { row, column, $index } = props
          return h('div', col.formatData(row, column, $index))
        }
      } else if (col.propEnum) {
        scopedSlots.default = props => {
          const { row } = props
          return h('c-dict-range-view', { props: {
            dictTypeCode: col.propEnum.dictTypeCode,
            value: row[col.prop],
            domainCode: col.propEnum.domainCode,
            appCode: col.propEnum.appCode
          }})
        }
      }
      return h('el-table-column', {
        props: {
          ...c
        },
        key: col.prop || i,
        scopedSlots
      })
    })
    if (this.multiple) {
      selectColumns.unshift(h('el-table-column', {
        props: {
          align: 'center',
          width: '70'
        },
        scopedSlots: {
          header: () => {
            return h('div', { class: 'empty', on: {
              click: () => this.removeSelectAll(elTable)
            }}, '清空')
          },
          default: props => {
            const { row, column, $index } = props
            return h('svg-icon', {
              class: 'close-icon',
              props: {
                iconClass: 'cuowuguanbiquxiao-solid_'
              },
              nativeOn: {
                click: e => {
                  this.removeSelectRow(row, column, $index)
                }
              }
            })
          }
        }
      }))
    }
    this.selectTable = selectTable
    const selectTable = h('el-table', { props: {
      data: this.selections,
      headerRowClassName: 'table-list-header',
      height: this.height
    }, on: {
      'row-click': this.rowClickHandle
    }}, selectColumns)
    return h('c-permission-tabs', { props: {
      refresh: false
    }}, [
      h('el-tab-pane', {
        props: {
          label: '待选择',
          name: 'noSelection'
        }
      }, [
        h('div', { class: 'table-box' }, [
          h('div', { class: 'table-list-box' }, [elTable]),
          h('div', { class: { more: true, finished: this.finished || !this.pageFlag }, on: { click: () => this.getData() }}, [
            h('span', this.finished || !this.pageFlag ? '没有更多了' : '加载更多'),
            h('i', { class: { 'el-icon-arrow-down': !(this.finished || !this.pageFlag) }})
          ])
        ])
      ]),
      h('el-tab-pane', {
        props: {
          label: `已选择(${this.selections.length})`,
          name: 'selection'
        }
      }, [h('div', { class: 'table-box' }, [
        h('div', { class: 'table-list-box' }, [selectTable])
      ])])
    ])
  }
}
</script>
<style lang="scss" scoped>
.empty{
  cursor: pointer;
  color: #3DC094;
}
.close-icon{
  cursor: pointer;
}
.more{
  color: #3DC094;
  padding-top: 10px;
  cursor: pointer;
}
.finished{
  color: #bebebe !important;
}
</style>
